package com.katze.boot.plugins.redis;

import org.springframework.data.redis.core.RedisTemplate;

import java.util.Map;

/**
 * 说  明：RedisTemplate 管理器
 * 作  者：zf.zeng
 * 日  期：2022-11-10 (星期四)
 **/
public class RedisTemplateManager<T> {
    private static final ThreadLocal<Integer> SELECT_CONTEXT = new ThreadLocal<>();
    private final Map<Integer, RedisTemplate<String, T>> redisTemplateMap;
    private final int database;

    public RedisTemplateManager(Map<Integer, RedisTemplate<String, T>> redisTemplateMap, int database) {
        this.redisTemplateMap = redisTemplateMap;
        this.database = database;
        SELECT_CONTEXT.set(this.database);
    }

    public RedisTemplate<String, T> primary() {
        return select(database);
    }

    /**
     * 需要开启Select Aspect
     * spring.redis.databases.dynamic-select = true
     * 通过AOP拦截 @SelectDB, 修改线程本地变量（ThreadLocal）, 达到动态切换database.初始取当前 spring.redis.database值
     */
    public RedisTemplate<String, T> current() {
        return select(SELECT_CONTEXT.get());
    }

    public RedisTemplate<String, T> select(Integer dbIndex) {
        if (dbIndex == null) {
            throw new NullPointerException("The Database " + dbIndex + " of Redis Template Not Found");
        } else {
            return redisTemplateMap.get(dbIndex);
        }
    }

    public static void setDatabase(Integer db) {
        SELECT_CONTEXT.set(db);
    }

    public static Integer getDatabase(){
        return SELECT_CONTEXT.get();
    }
}
